import { ElMessage } from 'element-plus'
import cookie from 'js-cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/index',
      name: 'Index',
      redirect: 'index/home',
      component: () => import('@/views/Index.vue'),
      children: [
        { path: 'redirect/:backpath(.*)', name: 'redirect', meta: { title: '' }, component: () => import('@/views/redirect/Index.vue') },
        { path: 'userinfo', name: 'userinfo', meta: { title: 'headportrait.personalinfor' }, component: () => import('@/components/userinfo/UserInfo.vue') },
        { path: 'modifypassword', name: 'ModifyPassword', meta: { title: 'headportrait.changepassword' }, component: () => import('@/views/admin/ModifyPassword.vue') },
      ],
    },
    // 登录页面 
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    // 404页面
    {
      path: '/404',
      component: () => import('@/views/404.vue')
    }
  ]
})

// 全局前置路由守卫
router.beforeEach((to, from) => {
  const token = cookie.get('token')
  if (!token && to.path != '/login') {
    router.replace({ path: '/login', query: { back: to.fullPath } })
    ElMessage.error('登录过期')
    return false
  }
  return true
})

export default router
